/**
 * 
 */
package com.p2p.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;

import com.p2p.base.cache.Cache;
import com.p2p.base.dao.BackendUserDao;
import com.p2p.base.global.DomainConst;
import com.p2p.base.model.BackendUser;
import com.p2p.base.service.LoginCountService;
import com.p2p.base.service.LoginLogService;
import com.p2p.base.util.AES;
import com.p2p.base.util.BasePropertyConfigurer;
import com.p2p.base.util.Const;
import com.p2p.base.util.CookieWrapper;
import com.p2p.base.util.LoginUtil;
import com.p2p.base.util.MD5Util;
import com.p2p.base.web.controller.BaseController;
import com.p2p.web.form.LoginForm;

/**
 * @author ruiqi
 *
 */
@RequestMapping("/backend")
@Controller
public class BackendLoginController extends BaseController{
	
	@Value("${p2p.backend_loginCookieName}")
	private String loginCookieName = "yqh_backend_ut";
	
	@Value("${p2p.backend_back_url}")
	private String defaultRedirectUrl = "";
	@Resource
	private Cache loginCache;
	
	@Resource
	private LoginLogService loginLogService;
	
	@Resource
	private LoginCountService loginCountService;
	
	@Resource
	BackendUserDao backendUserDao;
	
	@RequestMapping(value="/login")
	public String login(String backUrl,Model model,HttpServletRequest request,HttpServletResponse response) throws Exception{

		/*Assertion assertion = AssertionHolder.getAssertion();
		AttributePrincipal ap =  assertion.getPrincipal();
		String name = ap.getName();
		String key = AES.Encrypt(name, Const.KEY);
		CookieWrapper.setCookie(response, "yqh_ut", key, ".p2p.com", -1);
		BaseUser user = userService.findByName(name);
		if(loginRedis.exists(key)){
			loginRedis.delete(key);
		}
		loginRedis.add(key, user, 3, TimeUnit.MINUTES);
		return "redirect:"+backUrl;*/
		
		
		model.addAttribute("backUrl", backUrl);
		LoginForm loginForm = new LoginForm();
		model.addAttribute("loginForm", loginForm);
		return "backend/login";
	}
	
	@RequestMapping(value="/checklogin")
	public String checklogin(String backUrl,@Valid LoginForm loginForm,Errors errors, HttpServletRequest request,HttpServletResponse response) throws Exception{

		
		/*Assertion assertion = AssertionHolder.getAssertion();
		AttributePrincipal ap =  assertion.getPrincipal();
		String name = ap.getName();
		String key = AES.Encrypt(name, Const.KEY);
		CookieWrapper.setCookie(response, "yqh_ut", key, ".p2p.com", -1);
		BaseUser user = userService.findByName(name);
		if(loginRedis.exists(key)){
			loginRedis.delete(key);
		}
		loginRedis.add(key, user, 3, TimeUnit.MINUTES);
		return "redirect:"+backUrl;*/
		if(errors.hasErrors()){
			return "backend/login";
		}
		LoginUtil.setCurrentUser(null);
		checkPwd(loginForm.getLoginName(),loginForm.getLoginPswd(),errors);
		if(errors.hasErrors()){
			return "backend/login";
		}
		
		BackendUser user = (BackendUser)LoginUtil.getCurrentUser();
		
		LoginUtil.setCurrentUser(null);
		
		if(user!=null){
			loginCookie(user, response);
			if(StringUtils.isBlank(backUrl)){
				backUrl = this.defaultRedirectUrl;
			}
			return "redirect:"+backUrl;
			//return "redirect:redirect.html?backUrl="+backUrl;
		}
		return "backend/login";
	}
	
	private void loginCookie(BackendUser user,HttpServletResponse response) throws Exception{
		String key = AES.Encrypt(String.valueOf(user.getId()), Const.BackendLoginKEY);
		String p2p_domain_name = BasePropertyConfigurer.getContextProperty("p2p.domain");
		CookieWrapper.setCookie(response, loginCookieName, key, p2p_domain_name, -1);
		initPermition(user);
		loginCache.add(key, user, 3*60);
	}
	
	private void initPermition(BackendUser user){
		Long uid = user.getId();
		List<String> permitList = backendUserDao.findPrivilegeByUserId(uid);
		user.setPermitList(permitList);
	}
	
	/*//注册之后，带token标志位跳转到这里，解析token为3部分，校验通过，设置cookie，最后跳转到个人主页
	@RequestMapping(value="/tokenlogin")
	public String tokenLogin(@RequestParam String token, @RequestParam String backUrl,HttpServletResponse response) throws Exception{
		if(StringUtils.isNotEmpty(token) || StringUtils.isNotEmpty(backUrl)){
			String decryptToken=Encrypter.decrypt(token);
			//0-uname,1-salt,2-date
			String[] tokenArray = decryptToken.split(",");
			//Token标志位必须一致
			boolean tokenSame = tokenArray[1].equals(LoginToken.DEFAULT_SALT);
			//注册当天
			boolean dateSame=false;
			try {
				Date tokenDate=DateUtil.parseStandardDate(tokenArray[2]);
				dateSame=DateUtil.isSameDay(tokenDate, new Date());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if(tokenSame && dateSame){
				BaseUser user = userService.findByLoginName(tokenArray[0]);
				loginCookie(user, response);
				return "redirect:"+backUrl;
			}
		}
		
		return "login/login";
	}*/
	
	
	private void checkPwd(String loginName,String pwStr,Errors errors){
		BackendUser user = backendUserDao.findByLoginName(loginName);
		String errorTip = "用户名或密码不正确";
		if(user==null){		
			errors.rejectValue("loginName","no_exist" , errorTip);
			return;
		}
		String checkPwd = MD5Util.sha1(pwStr);
		if(StringUtils.equals(user.getPassword(), checkPwd)){
			LoginUtil.setCurrentUser(user);
		}else{
			errors.rejectValue("loginPswd","wrong_password",errorTip);
			return;
		}
	}
	@RequestMapping(value="/logout")
	public String logout(String backUrl,Model model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		String value = CookieWrapper.getCookieValue(request, loginCookieName);
		String name = AES.Decrypt(value, Const.BackendLoginKEY);
		CookieWrapper.clearCookie(response, loginCookieName, DomainConst.p2p_domain_name);
		if(loginCache.exists(name)){
			loginCache.delete(name);
		}
		LoginForm loginForm = new LoginForm();
		model.addAttribute("loginForm", loginForm);
		return "backend/login";
	}

}
